import { PERMISSION_ID_ENUM } from "../enums";
import { goAppPermissionSetting, goSystemGPSSetting } from "../links";
import {
  checkDevicePermission,
  invokeAndroidSystemAuthorizationPopup,
  invokeIOSSystemAuthorizationPopup,
} from "../main";
import {
  getAuthNotesRecordByPermissionId,
  setAuthNotesRecordByPermissionId,
} from "../record";
import { queryPermissionCheckedResultByPermissionId } from "../tools/query";

import type { IConfig } from "../types";

/** 权限校验通用流程 */
export const authorityCheckingCommonFLow = (
  options: Omit<IConfig, "authorityDetails"> = {
    permissionId: PERMISSION_ID_ENUM.CAMERA,
    noteDialogConfig: {},
    settingDialogConfig: {},
  }
): Promise<boolean | Error> => {
  const { permissionId, noteDialogConfig, settingDialogConfig } = options;
  return new Promise((resolve, reject) => {
    try {
      // 若申请的权限组，则都需满足
      const permissionIds = Array.isArray(permissionId)
        ? permissionId.filter(
            (id): id is PERMISSION_ID_ENUM => id !== undefined
          )
        : [permissionId].filter(
            (id): id is PERMISSION_ID_ENUM => id !== undefined
          );

      const permissionResultList = permissionIds.map(
        (id: PERMISSION_ID_ENUM) => ({
          ...checkDevicePermission(id),
          permissionId: id,
        })
      );
      console.log("permissionResultList>>>>>>>>>", permissionResultList);
      const res = permissionResultList.every(
        (permissionResItem) => permissionResItem?.data
      );
      console.log("是否开启权限 res>>>>>>>>>", res);
      // 是否开启权限
      if (!res) {
        // 判断是否同意过告知弹窗，若为权限组时，需全部同意
        const agree = getAuthNotesRecordByPermissionId(
          permissionId as string | string[]
        );
        if (agree) {
          uni.showModal({
            cancelText: "拒绝",
            confirmText: "去设置",
            ...settingDialogConfig,
            success: ({ confirm }) => {
              if (confirm) {
                // 定位特殊处理，GPS和应用定位授权跳转不同设置页
                const gpsPermissionRes =
                  queryPermissionCheckedResultByPermissionId(
                    permissionResultList,
                    PERMISSION_ID_ENUM.GPS
                  );
                if (gpsPermissionRes && !gpsPermissionRes.data) {
                  goSystemGPSSetting();
                  resolve(false);
                  return;
                }
                goAppPermissionSetting();
              }
              resolve(false);
            },
          });
          return;
        }
        const platform = plus.os.name.toLocaleLowerCase();
        if (platform === "ios") {
          let result = true;
          // 特殊处理gps，不需要调用授权弹窗
          const processPermissionId = permissionIds.filter(
            (id) => id !== PERMISSION_ID_ENUM.GPS
          );
          invokeIOSSystemAuthorizationPopup(processPermissionId).then(
            (iosResult) => {
              result = iosResult?.data;
              setAuthNotesRecordByPermissionId(permissionId as string, true);
              resolve(result);
            }
          );
          return;
        }
        // 未同意过告知弹窗
        uni.showModal({
          cancelText: "取消",
          confirmText: "继续",
          ...noteDialogConfig,
          success: async ({ confirm, cancel }) => {
            if (confirm) {
              let result = true;
              // 安卓、ios端都需手动调用唤起授权弹窗
              // const platform = plus.os.name.toLocaleLowerCase();
              switch (platform) {
                case "android": {
                  const androidResult =
                    await invokeAndroidSystemAuthorizationPopup(
                      permissionId as string
                    );
                  result = androidResult.success;
                  break;
                }
                /**
                 * @deprecated
                 * START iOS此逻辑废弃, 原因是 AppleConnect 官方审核对此流程的设计表示反对，不通过审核
                 */
                case "ios":
                default: {
                  // 特殊处理gps，不需要调用授权弹窗
                  const processPermissionId = permissionIds.filter(
                    (id) => id !== PERMISSION_ID_ENUM.GPS
                  );
                  const iosResult = await invokeIOSSystemAuthorizationPopup(
                    processPermissionId
                  );
                  result = iosResult?.data;
                  break;
                }
                /** END */
              }
              setAuthNotesRecordByPermissionId(permissionId as string, true);
              resolve(result);
            }
            if (cancel) {
              resolve(false);
            }
          },
        });
        return;
      }
      resolve(true);
    } catch (error) {
      reject(error);
    }
  });
};
